<template>
  <view class="oreo-page">
    <oreo-popup v-if="state.avatarShow" round :show="state.avatarShow" position="bottom">
      <avatar-popup
        class="avatar-popup"
        :userInfo="userInfo"
        @close="handleOpenWebsite"
      />
    </oreo-popup>
    <web-view v-else :src="src" @message="handleViewMessage"></web-view>
  </view>
</template>
<script setup>
import { onLoad, onShareAppMessage } from "@dcloudio/uni-app";
import { onMounted, reactive, ref } from "vue";
import { ossImg } from "@/utils/utils";
import { config } from './config'
import { ObjectToQueryString } from '@/utils/utils'
import AvatarPopup from './components/avatar-popup.vue'

const state = reactive({
  avatarShow: false
})
const userInfo = ref({})
const src = ref("");
const sceneObj = reactive({ scene: "", wx_scene: 0, q: '' })
const shareParams = reactive({ team_id: "", team_type: "" })

const getQueryParams = (user = {}, exactParams = {}, shareParams = {}) => ({
  'accesstoken': uni.getStorageSync("TOKEN"),
  'openid': uni.getStorageSync("OPENID"),
  'unionid': uni.getStorageSync("UNIONID"),
  'memberid': user?.memberScore?.memberId || '',
  'agree': 'true',
  ...exactParams,
  ...shareParams
})

onLoad(options => {
  getApp().accessLogAdd();
  shareParams.team_id = options?.team_id || ''
  shareParams.team_type = options?.team_type || ''
  sceneObj.scene = options?.scene || ""
  sceneObj.wx_scene = uni.getLaunchOptionsSync().scene
  sceneObj.q = options.q || ''
})

onMounted(async () => {
  await getApp().getUserLoginInfo()
  userInfo.value = await getApp().getUserInfo()
  if (
    userInfo.value.nickname === "微信用户" ||
    userInfo.value.icon === "" ||
    userInfo.value.icon === process.env.OSS_IMG + "personal/moren_avatar.png"
  ) {
    state.avatarShow = true;
    return
  }
  handleOpenWebsite()
})

const handleOpenWebsite = () => {
  console.log(shareParams)
  state.avatarShow = false
  const params = getQueryParams(userInfo.value, sceneObj, shareParams)
  src.value = `${config.hostname}?${ObjectToQueryString(params)}`
}

const handleViewMessage = ({ detail }) => {
  Object.assign(shareParams, detail.data?.at(-1) || {})
}

onShareAppMessage(() => {
  const { team_id, team_type } = shareParams
  const path = team_id
    ? `/campaign/pages/oreo-destiny/index?scene=KJQUTAUL734Z4OJIPPD5D908B4&team_id=${team_id || ''}&team_type=${team_type || ''}`
    : `/campaign/pages/oreo-destiny/index?scene=KJYZVFAJBSX5TSUGY88AV4PAJA`
  console.log(path)
  return {
    title: team_id ? '万物皆可搭，助攻领好礼！' : '万物皆可搭！找搭子速戳！',
    imageUrl: ossImg(`others/oreo-destiny/${team_id ? 'team_share' : 'share_cover2'}.jpg`),
    path
  }
})
</script>

<style lang="scss">
  .oreo-page {
    width: 100%;
    height: 100vh;
  }
</style>
